﻿using UnityEngine;
using UnityEngine.UI;

namespace Jinndev {

    public class AutoDisableImage : MonoBehaviour {

        private RawImage rawImage;
        private Image image;

        private Texture texture;
        private Sprite sprite;

        private void Awake() {
            rawImage = GetComponent<RawImage>();
            image = GetComponent<Image>();
        }

        private void OnEnable() {
            if (rawImage != null) {
                texture = rawImage.texture;
                rawImage.enabled = texture != null;
            }
            if (image != null) {
                sprite = image.sprite;
                image.enabled = sprite != null;
            }
        }

        private void OnDestroy() {
            rawImage = null;
            image = null;
            texture = null;
            sprite = null;
        }

        private void LateUpdate() {
            if (rawImage != null) {
                if (rawImage.texture != texture) {
                    texture = rawImage.texture;
                    rawImage.enabled = texture != null;
                }
            }
            else if (image != null) {
                if (image.sprite != sprite) {
                    sprite = image.sprite;
                    image.enabled = sprite != null;
                }
            }
        }

    }

}
